package com.sxj.PDMS.controller.admin;

import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.model.entity.DevelopTheObjectApplicationInformationList;
import com.sxj.PDMS.model.vo.NoticeResponse;
import com.sxj.PDMS.model.entity.Notice;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import org.springframework.web.multipart.MultipartFile;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@CrossOrigin
@RestController
@RequestMapping("/notice")
@Slf4j
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    private final String uploadImgDir = "D:\\user\\Desktop\\store\\notice\\image\\";
    private final String uploadHtmlDir = "D:\\user\\Desktop\\store\\notice\\content\\";

    @PostMapping("/tinymce/upload")
    public Map<String, String> uploadFile(@RequestParam("file") MultipartFile file) {
        NoticeController.log.info("上传文件: {}", file);

        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

        try {
            File dest = new File(uploadImgDir, fileName);
            file.transferTo(dest);
            String fileUrl = "http://localhost:8080/notice/uploads/" + fileName;  // 替换为实际的文件访问路径

            Map<String, String> response = new HashMap<>();
            response.put("location", fileUrl);

            return response;
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
    }

    @GetMapping("/uploads/{fileName:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String fileName) {
        try {
            Path file = Paths.get(uploadImgDir).resolve(fileName);
            Resource resource = new UrlResource(file.toUri());

            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件不存在");
            }
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }

    @PostMapping("/tinymce/upload_notice")
    public BaseResponse uploadNotice(@RequestBody Map<String, String> payload) {
        // 非空判断
        if (payload.get("title") == null || payload.get("summary") == null || payload.get("content") == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        // todo 非空判断
        String title = payload.get("title");
        String summary = payload.get("summary");
        String content = payload.get("content");

        String dirPath = "D:\\user\\Desktop\\store\\notice\\content\\";
        String fileName = UUID.randomUUID().toString() + ".html";

        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, fileName);
        try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
            writer.write("<html><head><meta charset=\\\"UTF-8\\\"><title>" + title + "</title></head><body>");
            writer.write("<h1>" + title + "</h1>");
            writer.write("<p>" + summary + "</p>");
            writer.write(content);
            writer.write("</body></html>");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件保存失败");
        }

        LocalDateTime currentTime = LocalDateTime.now();
        Date createTime = Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant());

        // 保存到数据库
        Notice notice = new Notice();
        notice.setTitle(title);
        notice.setIntro(summary);
        notice.setContent(file.getPath()); // 保存文件路径或文件名，根据实际情况存储
        notice.setCreateTime(createTime);

        boolean saved = noticeService.save(notice);
        if (!saved) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "保存失败");
        }

        return Result.success();
    }

    //    @GetMapping("/content/{id}")
//    public ResponseEntity<byte[]> serveContent(@PathVariable Long id) {
//        try {
//            // 查询数据库获取 Notice 实体
//            Notice notice = noticeService.getById(id);
//            if (notice == null) {
//                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "该通知不存在");
//            }
//            // 获取文件名或路径
//            String fileName = notice.getContent();
//
//            // 构建文件路径
//            Path file = Paths.get(uploadHtmlDir).resolve(fileName);
//            Resource resource = new UrlResource(file.toUri());
//
//            // 读取文件内容为字节数组
//            byte[] data = Files.readAllBytes(file);
//
//            return ResponseEntity.ok()
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline")
//                    .body(data);
//        } catch (IOException e) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件读取失败");
//        }
//    }
    @GetMapping("/content/{id}")
    public ResponseEntity<String> serveContent(@PathVariable Long id) {
        NoticeController.log.info("查询公告id: {}", id);

        try {
            // 查询数据库获取 Notice 实体
            Notice notice = noticeService.getById(id);
            if (notice == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "该通知不存在");
            }
            // 获取文件名或路径
            String fileName = notice.getContent();

            // 构建文件路径
            Path file = Paths.get(uploadHtmlDir).resolve(fileName);
            String content = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "text/html")
                    .body(content);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件读取失败");
        }
    }


    /**
     * 获取所有通知的标题、简介和第一张图片的位置
     *
     * @return
     */
    @GetMapping("/tinymce/get_all_notice")
    public BaseResponse<PagingQueryResponse<NoticeResponse>> getAllNotices(@RequestParam(defaultValue = "1") Integer page,
                                                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<NoticeResponse> pagingQueryResponse = noticeService.getAllNotices(page, pageSize);

        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/tinymce/get13_notice")
    public BaseResponse<List<NoticeResponse>> get13Notices() {
        List<NoticeResponse> noticeResponses = new ArrayList<>();
        List<Notice> notices = noticeService.get6Notices();

        for (Notice notice : notices) {
            // 构建 NoticeResponse 对象，包含标题、简介和第一张图片的位置
            NoticeResponse noticeResponse = new NoticeResponse();
            noticeResponse.setId(notice.getId());
            noticeResponse.setTitle(notice.getTitle());
            noticeResponse.setSummary(notice.getIntro());
            noticeResponse.setCreateTime(notice.getCreateTime());

            // 获取通知内容中的第一张图片位置
            String firstImageUrl = extractFirstImageUrlFromFile(notice.getContent());
            noticeResponse.setFirstImageUrl(firstImageUrl);

            noticeResponses.add(noticeResponse);
        }

        return Result.success(noticeResponses);
    }

    @GetMapping("/tinymce/get46_notice")
    public BaseResponse<List<NoticeResponse>> get46Notices() {
        List<NoticeResponse> noticeResponses = new ArrayList<>();
        List<Notice> notices = noticeService.get46Notices();

        for (Notice notice : notices) {
            // 构建 NoticeResponse 对象，包含标题、简介和第一张图片的位置
            NoticeResponse noticeResponse = new NoticeResponse();
            noticeResponse.setId(notice.getId());
            noticeResponse.setTitle(notice.getTitle());
            noticeResponse.setSummary(notice.getIntro());
            noticeResponse.setCreateTime(notice.getCreateTime());

            // 获取通知内容中的第一张图片位置
            String firstImageUrl = extractFirstImageUrlFromFile(notice.getContent());
            noticeResponse.setFirstImageUrl(firstImageUrl);

            noticeResponses.add(noticeResponse);
        }

        return Result.success(noticeResponses);
    }

    @DeleteMapping("/tinymce/del_notice/{id}")
    public BaseResponse<String> deleteNotice(@PathVariable String id) {
        try {
            Long noticeId = Long.parseLong(id);
            log.info("删除通知：id = {}", noticeId);

            // 根据业务逻辑删除通知
            Boolean deleted = noticeService.deleteById(noticeId);

            if (deleted) {
                return Result.success("删除成功");
            } else {
                return Result.error(ErrorCode.SYSTEM_ERROR, "删除失败");
            }
        } catch (NumberFormatException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的通知ID：" + id);
        }
    }


    private String extractFirstImageUrlFromFile(String filePath) {
        try {
            // 读取文件内容为字符串
            String htmlContent = readFileToString(filePath);

            // 使用 Jsoup 解析 HTML 内容，获取第一张图片的地址
            return extractFirstImageUrl(htmlContent);
        } catch (IOException e) {
            log.error("读取文件内容失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 将文件内容读取为字符串
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    private String readFileToString(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        byte[] bytes = Files.readAllBytes(path);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private String extractFirstImageUrl(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        Elements imgElements = doc.select("img");

        if (imgElements != null && !imgElements.isEmpty()) {
            Element firstImg = imgElements.first();
            String imageUrl = firstImg.attr("src");
            return imageUrl;
        }

        return null; // 如果没有找到图片则返回 null
    }


}

